# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render

# Create your views here.

#省份信息
#select * from tb_areas where parent_id is null;
from rest_framework.response import Response
from rest_framework.views import APIView

# areas/infos/
from areas.models import Area
from areas.serializers import AreaSerializer, SubsAreaSerializer


class ProvienceAPIView(APIView):

    def get(self,request):

        #1.获取所有的省的数据    [Area,Area,Area]
        areas = Area.objects.filter(parent=None)
        #2. 将对象列表转换为字典列表
        serializer = AreaSerializer(areas,many=True)
        #3. 返回相应
        return Response(serializer.data)

#市
# select * from tb_areas where parent_id=130000;
#区县
# select * from tb_areas where parent_id=130600;

# areas/infos/pk/
class CityAPIView(APIView):

    def get(self,request,pk):

        #1. 获取指定数据  [Area,Area,Area]
        areas = Area.objects.filter(parent=pk)
        #2.将对象列表转换为 字典列表
        serialiaer = AreaSerializer(areas,many=True)
        #3.返回相应
        return Response(serialiaer.data)



#Django REST框架允许将一组相关视图的逻辑组合到一个类中，称为ViewSet
from rest_framework.mixins import ListModelMixin,RetrieveModelMixin
from rest_framework.viewsets import ReadOnlyModelViewSet

from rest_framework_extensions.cache.mixins import ListCacheResponseMixin,RetrieveCacheResponseMixin
from rest_framework_extensions.cache.mixins import CacheResponseMixin
class AreaModelViewSet(CacheResponseMixin,ReadOnlyModelViewSet):

    # queryset = Area.objects.filter(parent=None) # 省
    # queryset = Area.objects.all() #市，区县

    def get_queryset(self):
        # action   list,retrieve,update,delete,create
        # 我们的list 就是获取省的数据              areas/infos/
        # retrieve 就是获取 市，区县信息          areas/infos/pk/
        if self.action == 'list':
            # 省的信息
            return Area.objects.filter(parent=None)
        else:
            # 区县信息
            return Area.objects.all()

    # serializer_class = AreaSerializer
    # serializer_class = AreaSerializer   #省
    # serializer_class = SubsAreaSerializer   #市

    def get_serializer_class(self):

        if self.action == 'list':
            return AreaSerializer
        else:
            return SubsAreaSerializer


# from areas.models import Area
# area = Area.objects.get(id=130000)
from rest_framework.mixins import RetrieveModelMixin
from rest_framework.generics import GenericAPIView
"""

filter_kwargs = {'pk': 130000}
obj = get_object_or_404(queryset, **filter_kwargs)
# 省的对象
# 通过省的对象.area_set
# 来获取市的信息

obj = Area.objects.get(pk=130000)
"""
# 1s 10 省份查询